<template>
  <div class="record-container">
    <!-- 搜索和分页控件 -->
    <div class="searchBox">
      <el-form :inline="true" :model="queryParams" class="demoFormInline">
        <el-form-item label="筛选类型">
          <el-select 
            v-model="queryParams.Category" 
            placeholder="请选择" 
            @change="onSelectCustom"
            style="width: 150px;">
            <el-option label="招商员" value="1"></el-option>
            <el-option label="部门" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="queryParams.dateRanges"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 320px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">查询</el-button>
          <el-button icon="Refresh" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="content-layout">
      <!-- 图表数据 -->
      <div class="chart-section">
        <div class="echarts-card" v-loading="echartsLoading">
          <el-card class="box-card" shadow="never">
            <div id="main" style="height:350px;"></div>
            <div id="main1" style="height:300px;"></div>
          </el-card>
        </div>
      </div>

      <!-- 数据表格 -->
      <div class="table-section">
        <div class="tableContainer" >
          <el-table :data="tableData" border style="width: 100%" v-loading="loading" 
            show-summary
            :summary-method="getSummaries"
            :height="350"
            >
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column prop="name" :label="nameColumnLabel" min-width="120" />
            <el-table-column prop="addCustomer" label="新增客户数(个)" min-width="80" />
            <el-table-column prop="homeVisit" label="拜访数(个)" min-width="120" />
            <el-table-column prop="visitReception" label="来访数(个)" min-width="120" />
            <el-table-column prop="verifiedCustomer" label="核名客户数(个)" min-width="200" show-overflow-tooltip />

          </el-table>
        </div>
        
        <!-- 分页组件 -->
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="fetchData"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { getVisualizationInvestmentData } from "@/api/AttractInvestment/contact/index.js";
import * as echarts from 'echarts';
import { start } from "nprogress";
const nameColumnLabel = computed(() => {
  return queryParams.Category == '1' ? '招商员' : '部门';
});

// 图表实例引用
const chart1 = ref(null);
const chart2 = ref(null);
const echartsLoading = ref(false);

// 图表数据
const chartData = reactive({
  dailyData: [],
  followUpData: {}
});

// 路由
const router = useRouter();

// 计算近七天的日期范围
const getLastSevenDays = () => {
  const end = new Date();
  const start = new Date();
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
  return [start, end];
};

// 查询参数
const queryParams = reactive({
  Category: "1",
  dateRanges: getLastSevenDays(),
  pageNum: 1,
  pageSize: 10
});

// 表格数据
const tableData = ref([]);
// 分页信息
const total = ref(0);
// 加载状态
const loading = ref(false);

// 格式化日期显示
const formatDateForDisplay = (dateStr) => {
  const date = new Date(dateStr);
  return `${date.getMonth() + 1}-${date.getDate()}`;
};

// 更新图表数据
const updateCharts = () => {
  // 更新柱状图（每日新增客户）
  if (chart1.value) {
    const dates = chartData.dailyData.map(item => formatDateForDisplay(item.date));
    const dailyCounts = chartData.dailyData.map(item => item.dailyCount);
    
    const option1 = {
      title: {
        text: '每日新增客户统计'
      },
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          const data = chartData.dailyData[params[0].dataIndex];
          return `${data.date.split(' ')[0]}<br/>新增客户: ${data.dailyCount}`;
        }
      },
      xAxis: {
        type: 'category',
        data: dates,
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        name: '客户数'
      },
      series: [
        {
          name: '新增客户',
          type: 'bar',
          data: dailyCounts,
          itemStyle: {
            color: '#5470c6'
          }
        }
      ]
    };
    chart1.value.setOption(option1);
  }

  // 更新饼图（跟进类型分布）
  if (chart2.value) {
    const followUpData = chartData.followUpData;
    const option2 = {
      title: {
        text: '客户跟进类型分布'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        top: 'bottom'
      },
      series: [
        {
          name: '跟进类型',
          type: 'pie',
          radius: ['40%', '70%'],
          data: [
            { value: followUpData.nameVerificationCount || 0, name: '核名数' },
            { value: followUpData.visitCount || 0, name: '拜访数' },
            { value: followUpData.receptionCount || 0, name: '来访数' },
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
    chart2.value.setOption(option2);
  }
};

// 初始化图表
const initCharts = () => {
  // 销毁已存在的图表实例
  if (chart1.value) {
    chart1.value.dispose();
  }
  if (chart2.value) {
    chart2.value.dispose();
  }

  // 初始化第一个图表（柱状图）
  const chartDom1 = document.getElementById('main');
  if (chartDom1) {
    chart1.value = echarts.init(chartDom1);
  }

  // 初始化第二个图表（饼图）
  const chartDom2 = document.getElementById('main1');
  if (chartDom2) {
    chart2.value = echarts.init(chartDom2);
  }

  // 更新图表数据
  updateCharts();
};
// 添加日期格式化函数
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
// 获取数据
const fetchData = async () => {
  loading.value = true;
  echartsLoading.value = true;
  
  try {
    console.log('queryParams：', queryParams);
    // 修改
     const requestParams = {
      ...queryParams,
      startTime: queryParams.dateRanges && queryParams.dateRanges[0] 
        ? formatDate(queryParams.dateRanges[0]) 
        : '',
      endTime: queryParams.dateRanges && queryParams.dateRanges[1] 
        ? formatDate(queryParams.dateRanges[1]) 
        : ''
    };
    console.log('queryParams：', queryParams);
    console.log('queryParams：', requestParams);
    const res = await getVisualizationInvestmentData(requestParams);
    
    if (res && res.code == 200 && res.data) {
      const pageData = res.data;
      
      // 更新表格数据
      let rows = [];
      if (Array.isArray(pageData.list)) {
        rows = pageData.list.map(item => ({
          name: item.name,
          addCustomer: item.addCustomer,
          verifiedCustomer: item.verifiedCustomer,
          visitReception: item.visitReception,
          homeVisit: item.homeVisit
        }));
      }
      tableData.value = rows;
      total.value = pageData.total || 0;
      
      // 更新图表数据
      chartData.dailyData = pageData.customAddNum || [];
      chartData.followUpData = pageData.followUpNum || {};
      
      // 重新渲染图表
      setTimeout(() => {
        initCharts();
      }, 100);
      
    } else {
      tableData.value = [];
      total.value = 0;
      chartData.dailyData = [];
      chartData.followUpData = {};
      initCharts();
    }
  } catch (error) {
    console.error("获取数据失败:", error);
    tableData.value = [];
    total.value = 0;
    chartData.dailyData = [];
    chartData.followUpData = {};
    initCharts();
  } finally {
    loading.value = false;
    echartsLoading.value = false;
  }
};
// 表格总计计算方法
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '总计';
      return;
    }
    if (index === 1) {
      sums[index] = '';
      return;
    }
    const values = data.map(item => Number(item[column.property]));
    if (!values.every(value => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0);
    } else {
      sums[index] = '';
    }
  });

  return sums;
};

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1; // 重置到第一页
  fetchData();
};

// 重置表单
const resetForm = () => {
  Object.assign(queryParams, {
    Category: "1",
    dateRanges: getLastSevenDays(),
    pageNum: 1
  });
  fetchData();
};

// 选择类型变化
const onSelectCustom = () => {
  fetchData();
};

// 窗口大小改变时的处理
const handleResize = () => {
  chart1.value?.resize();
  chart2.value?.resize();
};

// 监听窗口大小变化
window.addEventListener('resize', handleResize);

// 组件挂载时获取数据
onMounted(() => {
  fetchData();
});

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (chart1.value) {
    chart1.value.dispose();
  }
  if (chart2.value) {
    chart2.value.dispose();
  }
});
</script>

<style scoped>
.record-container {
  padding: 20px;
}

.searchBox {
  margin-bottom: 20px;
}

.tableContainer {
  margin-bottom: 20px;
}

.content-layout {
  display: flex;
  gap: 20px;
}

.chart-section {
  flex: 1;
}

.table-section {
  flex: 1;
}

@media (max-width: 768px) {
  .content-layout {
    flex-direction: column;
  }
}

/* 确保图表容器正确显示 */
#main, #main1 {
  width: 100%;
}
/* 修改 tableContainer 样式 */
.tableContainer {
  margin-bottom: 20px;
  height: 350px; /* 设置固定高度 */
  overflow-y: auto; /* 启用垂直滚动 */
  border: 1px solid #ebeef5;
}

/* 确保表格宽度适配容器 */
.el-table {
  width: 100% !important;
}
</style>